package com.gxz.controller;

import com.github.pagehelper.PageInfo;
import com.gxz.common.BasePageInfo;
import com.gxz.common.Result;
import com.gxz.pojo.User;
import com.gxz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id) {
        System.out.println("进入controller getById" + id);
        try {
            User user = userService.getById(id);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping
    public Result getAll(@RequestBody BasePageInfo basePageInfo) {
        try {
            PageInfo<User> list = userService.getAll(basePageInfo);
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @PostMapping
    public Result create(@RequestBody User user) {
        try {
            Integer i = userService.create(user);
            if (i > 0) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            Integer i = userService.update(user);
            if (i > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id) {
        try {
            Integer i = userService.delete(id);
            if (i > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}
